package com.macro.mall.tiny.modules.bms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.modules.bms.mapper.AdvertMapper;
import com.macro.mall.tiny.modules.bms.model.Advert;
import com.macro.mall.tiny.modules.bms.service.AdvertService;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 广告信息表 服务实现类
 * </p>
 *
 * @author macro
 * @since 2025-11-21
 */
@Service
public class AdvertServiceImpl extends ServiceImpl<AdvertMapper, Advert> implements AdvertService {

    @Autowired
    private AdvertMapper advertMapper;

    @Override
    public CommonPage<Advert> getPageList(Integer positionId, String name, LocalDateTime startTime, LocalDateTime endTime, Integer pageNum, Integer pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Advert> advertList = advertMapper.selectPageList(positionId, name, startTime, endTime, offset, pageSize);
        int totalCount = advertMapper.selectTotalCount(positionId, name, startTime, endTime);
        int totalPage = (int) Math.ceil((double) totalCount / pageSize);
        
        Page<Advert> page = new Page<>(pageNum, pageSize);
        page.setRecords(advertList);
        page.setTotal(totalCount);
        page.setPages(totalPage);
        
        return CommonPage.restPage(page);
    }

    @Override
    public boolean create(Advert advert) {
        advert.setCreatedAt(LocalDateTime.now());
        advert.setUpdatedAt(LocalDateTime.now());
        return this.save(advert);
    }

    @Override
    public boolean update(Long id, Advert advert) {
        advert.setId(id.intValue());
        advert.setUpdatedAt(LocalDateTime.now());
        return this.updateById(advert);
    }

    @Override
    public boolean delete(Long id) {
        Advert advert = new Advert();
        advert.setId(id.intValue());
        advert.setDelFlag(1);
        advert.setUpdatedAt(LocalDateTime.now());
        return this.updateById(advert);
    }

    @Override
    public List<Advert> getActiveAdvertsByPositionId(Integer positionId) {
        return advertMapper.selectActiveAdvertsByPositionId(positionId);
    }
}